package com.zretc.support.dao;


import com.zretc.support.entity.Reply;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;

import java.io.Serializable;
import java.util.Date;
import java.util.List;


public interface ReplyDao extends JpaRepository<Reply, String>, JpaSpecificationExecutor<Reply>,
        Serializable {
    /**
     * 根据问题编号进行查询分页
     * @param questionId
     * @param startTime
     * @param endTime
     * @return
     */
    @Query("select r from Reply r inner join Question q on r.question.questionId = q.questionId " +
            "inner join User u on r.user.userId = u.userId where r.question.questionId= ?1 and " +
            "r.replyTime between ?2 and ?3")
    Page<Reply> getReplyByQuestionIDAndPage(long questionId, Date startTime, Date endTime, Pageable pageable);

    /**
     * 根据用户名进行模糊查询+分页
     * @param userName
     * @param startTime
     * @param endTime
     * @return
     */
    @Query("select r from Reply r inner join Question q on r.question.questionId = q.questionId " +
            "inner join User u on r.user.userId = u.userId where r.user.userName like  %?1% and " +
            "r.replyTime between ?2 and ?3")
    Page<Reply> getReplyByUserNameAndPage(String userName, Date startTime, Date endTime, Pageable pageable);

    /**
     * 根据以及问题内容时间区间查询+分页
     * @param startTime
     * @param endTime
     * @param pageable
     * @return
     */
    @Query("select r from Reply r inner join Question q on r.question.questionId = q.questionId " +
            "inner join User u on r.user.userId = u.userId where r.replyContent like %?1% and r.replyTime between ?2 and ?3")
    Page<Reply> getRepliesByTime(String replyContent, Date startTime, Date endTime, Pageable pageable);

    Reply findReplyByReplyId(long replyId);


    /**
     * 查询第一次留言的信息
     * @param questionId
     * @param pageable
     * @return
     */
    @Query("select r from Reply r inner join Question q on r.question.questionId = q.questionId " +
            "inner join User u on r.user.userId = u.userId where r.question.questionId = ?1 and r.parentId is null order by r.replyTime desc ")
    Page<Reply> getReplyWithoutPid(long questionId,Pageable pageable);

    /**
     * 查询留言的留言
     * @param parentId
     * @return
     */
    @Query("select r from Reply r inner join Question q on r.question.questionId = q.questionId " +
            "inner join User u on r.user.userId = u.userId where r.parentId = ?1 order by r.replyTime desc ")
    List<Reply> getReplyRe(long parentId);

    /**
     * 统计问题下的回复数
     * @param questionId
     * @return
     */
    int countRepliesByQuestion_QuestionId(Long questionId);
}

